<?php

namespace App\Models;

use Illuminate\Support\Facades\Cache;

class AdminUser extends BaseModel
{

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'update_time';
    const ADMIN_USER_INFO = 'admin:user:';
    const LOGIN_KEY = 'admin:login:';

    protected $table = 'admin_user';

    /**
     * 指示是否自动维护时间戳
     *
     * @var bool
     */
    public $timestamps = true;
    protected $dateFormat = 'U';
    

    // 列表返回字段
    protected static $listField = 'id, account, user_name, head_pic, sex, role_id, status, last_login_time, create_time, update_time';

    /**
     * 通过uid获取用户信息
     */
    public function userInfo($id)
    {
        $seconds = 3600*24;
        return cache()->remember(self::ADMIN_USER_INFO.$id, $seconds, function () use ($id) {
            $result =  $this -> from('admin_user as u')
                -> select('u.id', 'u.account', 'u.user_name', 'u.sex', 'u.head_pic', 'u.role_id', 'u.status', 'u.last_login_time', 'u.create_time', 'u.update_time', 'r.role_name', 'r.menu_ids')
                -> leftJoin('admin_role as r', 'r.id', '=', 'u.role_id')
                -> where(['u.id' => $id])
                -> first() -> toArray();
            return $result;
        });
    }

    /**
     * 根据token获取用户信息
     */
    public function tokenToInfo($token)
    {
        if (!$id = Cache::get(self::LOGIN_KEY.$token)) return false;
        return $this->userInfo($id);
    }

    /**
     * 修改信息同时清除缓存
     */
    public function updateInfo(array $data, array $where)
    {
        $result = $this -> where($where) -> update($data);
        if ($result && isset($where['id'])) Cache::forget(self::ADMIN_USER_INFO.$where['id']);
        return $result;
    }

}